package mysql

import (
	"errors"
	"gorm.io/gorm"
	"user_srv/global"
	"user_srv/pkg"
)

// 用户表
type User struct {
	gorm.Model
	Mobile   string `gorm:"column:mobile;type:char(11);unique;not null;comment:手机号"`
	Password string `gorm:"column:password;type:char(150);not null;comment:密码"`
	NickName string `gorm:"column:nick_name;type:varchar(100);not null;comment:昵称"`
	BirthDay int64  `gorm:"column:birth_day;type:int(11);not null;comment:生日"`
	Gender   string `gorm:"column:gender;type:varchar(10);not null;comment:性别"`
	Role     int64  `gorm:"column:role;type:int(11);not null;comment:角色"`
}

var err error

// 注册
func (u *User) RegisterUser() error {
	res := global.DB.Create(&u)
	if res.RowsAffected != 1 || res.Error != nil {
		return err
	}
	return nil
}

// 用手机号查询用户是否存在
func GetUserDetailByMobile(mobile string) (u *User, err error) {
	res := global.DB.Where("mobile = ?", mobile).Limit(1).Find(&u)
	if res.Error != nil {
		return nil, errors.New("数据库异常")
	}
	return u, nil
}

// 查询用户列表
func GetUserList(page, pageSize int) (u []*User, err error, num int64) {
	var count int64
	res := global.DB.Model(User{}).Scopes(pkg.Paginate(page, pageSize)).Find(&u).Count(&count)
	if res.Error != nil {
		return nil, err, 0
	}
	return u, nil, count
}

// 更新用户信息
func UpdateUser(u *User) error {
	res := global.DB.Model(User{}).Where("id = ?", u.ID).Updates(User{
		Mobile:   u.Mobile,
		Password: u.Password,
		NickName: u.NickName,
		BirthDay: u.BirthDay,
		Gender:   u.Gender,
		Role:     u.Role,
	})
	if res.Error != nil {
		return err
	}
	return nil
}
